<div class="container">
  <div class="col-md-8 col-md-offset-2">
    <div class="panel panel-default">
      <div class="panel-heading">
      新消息
      </div>
      <%- partial('components/unReadList') %>
      <div class="panel-footer">
        <a href="<%= apiPrefix.page %>/user/messages/all?type=unRead&appId=<%=appId%>">查看更多...</a>
      </div>
    </div>

    <div class="panel panel-default">
      <div class="panel-heading">
      已读消息
      </div>
      <%- partial('components/readList') %>
      <div class="panel-footer">
        <a href="<%= apiPrefix.page %>/user/messages/all?type=read&appId=<%=appId%>">查看更多...</a>
      </div>
    </div>
  </div>
</div>
<script>
  var appId = $('[name=app-id]').val();
  var pagePrefix = '<%= apiPrefix.page %>';
  var dataPrefix = '<%= apiPrefix.data %>';

  var vue = new Vue({
    el: '#app',
    data: {
      errorMsg: '',
      successMsg: '',
      read: {
        type: 'read',
        messages: [],
        currentPage: 1,
        pages: 1
      },
      unRead: {
        type: 'unRead',
        messages: [],
        currentPage: 1,
        pages: 1
      },
      canLoadData: true
    },
    methods: {
      getData: function(type, nextPage) {
        $.post(dataPrefix + '/message/data', {appId: appId, type: type, currentPage: nextPage}, function(result) {
          vue.canLoadData = true
          if (result.err) return vue.errorMsg = result.err
          result.data.forEach( function(item){
            if (type === 'read') {
              vue.read.messages.push(item)
            } else {
              vue.unRead.messages.push(item)
            }
          })
        })
      },
      onSetRead: function(index, id) {
        $.post(dataPrefix + '/message/read', {appId: appId, messageId: id}, function(result) {
          if (result.err) return vue.errorMsg = result.err
          else {
            vue.successMsg = result.msg
            vue.unRead.messages[index].has_read = true
          }
        })
      }
    }
  })

  vue.getData(vue.unRead.type, vue.unRead.currentPage);
  vue.getData(vue.read.type, vue.read.currentPage);
</script>
